package com.tianji.store.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.Result;
import com.tianji.store.mapper.SearchHistoryMapper;
import com.tianji.store.mapper.StoreMapper;
import com.tianji.store.pojo.SearchHistory;
import com.tianji.store.pojo.Store;
import com.tianji.store.pojo.vo.StoreVo;
import com.tianji.store.service.SearchHistoryService;
import com.tianji.store.service.StoreService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈佳
 * @since 2024-10-14
 */
@Service
@RequiredArgsConstructor
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    private final StoreMapper storeMapper;

    private final SearchHistoryService serviceSearchHistory;

    @Override
    public Result getStoreByName(String name, Integer page, Integer pageSize) throws ExecutionException, InterruptedException {
        StoreVo storeVo = new StoreVo();
        Page<Store> storePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name),Store::getName, name);
        Page<Store> pageResult = storeMapper.selectPage(storePage, queryWrapper);
        storeVo.setStores(pageResult);

        //异步保存搜索记录并且查询搜索记录
        CompletableFuture<List<SearchHistory>> future = CompletableFuture.supplyAsync(() -> saveSearchKeyword(name))
                .exceptionally(e -> {
                    log.error("保存搜索关键字时发生异常：" + e.getMessage());
                    return Collections.emptyList();
                });
        storeVo.setSearchHistories(future.get());
        return Result.success(storeVo);
    }

    public List<SearchHistory> saveSearchKeyword(String keyWord){
        SearchHistory searchHistory = new SearchHistory();
        searchHistory.setKeyword(keyWord);
        searchHistory.setSearchTime(LocalDateTime.now());
        serviceSearchHistory.save(searchHistory);
        LambdaQueryChainWrapper<SearchHistory> wrapper = serviceSearchHistory.lambdaQuery()
                .like(SearchHistory::getKeyword, keyWord)
                .orderByDesc(SearchHistory::getSearchTime);
        return serviceSearchHistory.list(wrapper);
    }
}
